<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class pro_desain_promo extends MY_Controller {
	
	function __construct()
	{
		parent::__construct(); 
		
		$this->load->model('pro_desain_promo_model', 'Desain');
		$this->secure_session();
	}
	
	function index(){
		$data['title'] = "Data Desain Promo";

		/*$query = $this->db->query("SELECT kode_desain FROM (SELECT * FROM pro_desain_promo ORDER BY kode_desain DESC) WHERE rownum <= 1");
		$getquery = $query->row_array();

		if($getquery)
			$MaxID = $getquery['kode_desain'];
		else
			$MaxID = "DS0000000";

		$NextID = (int) substr($MaxID,2,7);

		$NextID++;
		
		$data['kode_desain_auto'] = "DS" . sprintf("%07s",$NextID);*/

		viewByTemplate('pro_desain_promo/index', $data, 'grid');
	}
	

	function create()
	{
		// Display Form Create
		$data['title'] = "New Data Desain Promosi";
		$data['data'] = NULL;
		//$data['arr_reference']	= $this->Combo->SampleReference();
		$data['mode'] = "create";
		viewByTemplate('pro_desain_promo/form', $data, 'form');
	}

	function edit()
	{
		// Display Form Edit
		$data['title'] = "Ubah Data Desain Promosi";
		$data['data'] = $this->Desain->GetSingleView(get('kode_promosi'));
		
		// Define Combo Data
		$data['mode'] = "edit";
		viewByTemplate('pro_desain_promo/form', $data, 'form');
	}
	
	function view()
	{
		// Display Form View
		$data['title'] = "View Data Master";
		$data['data'] = $this->Desain->GetSingleView(get('kode_promosi'));
		
		$data['mode'] = "view";
		viewByTemplate('pro_desain_promo/form', $data, 'form');
	}
	

	function getdata()
	{
		$this->secure_session();
		echo $this->Desain->GetJSON();
	}

	private function validation()
	{
		$error = new ErrorList();

		// Get Error Template
		$tpl_empty = $this->MessageTemplate("ER001");
		$tpl_duplicate = $this->MessageTemplate("ER002");
		// Validation
		
		if (post("kode_promosi") == '') {
			$error->Add("kode_promosi", "Kode Tempat", $tpl_empty);
		} else if (post("mode") == "create" && intval($this->get_data("SELECT 1 FROM pro_desain_promo WHERE kode_promosi= '".@ereg_replace("[^a-zA-Z0-9_-]", "",@strtoupper(@trim(post("kode_promosi"))))."'")) > 0) {
			$error->Add("kode_promosi", "Kode Desain", $tpl_duplicate);
		}

		return $error;
	}
	
	function ajax_post()
	{
		$is_error = 0;
		$ls_response = "";
		$ls_genid = "";

		$error = $this->validation();
		try
		{
			if (count( $error->Get() ) > 0) { $is_error = 1; }
			else
			{
				// Fill Post Data
				$data	= post_by_key(array('kode_promosi', 'tanggal_permintaan', 'id_departemen_pk', 'nama_departemen', 'status_permintaan', 'nama_desain', 'jenis_desain', 'upload_desain', 'keterangan' ));
				
				$arr_tgl_perm = explode('/', $data['tanggal_permintaan']);
				$tanggal_permintaan = $arr_tgl_perm[2].'-'.sprintf("%02s",$arr_tgl_perm[1]).'-'.sprintf("%02s",$arr_tgl_perm[0]);
				
				$data['tanggal_permintaan'] = $tanggal_permintaan;

				$data['kode_promosi']	= @ereg_replace("[^a-zA-Z0-9_-]", "",@strtoupper(@trim($data['kode_promosi'])));
				
				if (post("mode") == "create")
				{
					$this->Desain->Add($data);

					$ls_response = "Data Tersimpan";

				}
				else if (post("mode") == "edit")
				{
					
					$this->Desain->Update($data, array('kode_promosi'	=> $data['kode_promosi']));

					$ls_response = "Data Tersimpan [edited]";
				}
			}
		} catch(Exception $e) {
			$is_error = $ls_response = $e->getMessage();
		}
		
		echo $this->PostResponse(json_encode(array(	'is_error'	=> $is_error,
													'fields'	=> $error->GetDictionary(),
													'msg'		=> $ls_response,
													'genid'		=> $ls_genid,
													'form_sender'=> post("form_sender"))
								));
	}

	function ajax_delete()
	{
		$ls_result	= "";
		$kode_promosi	= get('kode_promosi');
		
		if ($kode_promosi != "")
		{
			// Delete Single
			$arr_rule	= array('kode_promosi' => $kode_promosi);
			$ls_result = $this->Desain->DeleteSingle($arr_rule);

		}
		else
		{	
			
			$num_row = intval($this->data['num_row']['deleted']);
			
			for ($i = 0; $i < $num_row; $i++)
			{
				$row	= $this->data['deleted'][$i];
				
				$arr_rule	= array('kode_promosi' => $row['kode_promosi']);
				$ls_result .= $this->Desain->DeleteSingle($arr_rule);
			}
		}
		echo $ls_result;
	}

	// function processupload()
	// {
	// 	############ Edit settings ##############
	// 	$ThumbSquareSize 		= 200; //Thumbnail will be 200x200
	// 	$BigImageMaxSize 		= 500; //Image Maximum height or width
	// 	$ThumbPrefix			= "thumb_"; //Normal thumb Prefix
	// 	$DestinationDirectory	= APPPATH . 'file/desain/'; //specify upload directory ends with / (slash)
	// 	$Quality 				= 90; //jpeg quality
	// 	##########################################
		
	// 	//check if this is an ajax request
	// 	if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
	// 		die();
	// 	}
		
	// 	// check $_FILES['ImageFile'] not empty
	// 	if(!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name']))
	// 	{
	// 			die('Something wrong with uploaded file, something missing!'); // output error when above checks fail.
	// 	}
		
	// 	// Random number will be added after image name
	// 	$RandomNumber 	= rand(0, 9999999999); 

	// 	$ImageName 		= str_replace(' ','-',strtolower($_FILES['ImageFile']['name'])); //get image name
	// 	$ImageSize 		= $_FILES['ImageFile']['size']; // get original image size
	// 	$TempSrc	 	= $_FILES['ImageFile']['tmp_name']; // Temp name of image file stored in PHP tmp folder
	// 	$ImageType	 	= $_FILES['ImageFile']['type']; //get file type, returns "image/png", image/jpeg, text/plain etc.

	// 	//Let's check allowed $ImageType, we use PHP SWITCH statement here
	// 	switch(strtolower($ImageType))
	// 	{
	// 		case 'image/png':
	// 			//Create a new image from file 
	// 			$CreatedImage =  imagecreatefrompng($_FILES['ImageFile']['tmp_name']);
	// 			break;
	// 		case 'image/gif':
	// 			$CreatedImage =  imagecreatefromgif($_FILES['ImageFile']['tmp_name']);
	// 			break;			
	// 		case 'image/jpeg':
	// 		case 'image/pjpeg':
	// 			$CreatedImage = imagecreatefromjpeg($_FILES['ImageFile']['tmp_name']);
	// 			break;
	// 		default:
	// 			die('Unsupported File!'); //output error and exit
	// 	}
		
	// 	//PHP getimagesize() function returns height/width from image file stored in PHP tmp folder.
	// 	//Get first two values from image, width and height. 
	// 	//list assign svalues to $CurWidth,$CurHeight
	// 	list($CurWidth,$CurHeight)=getimagesize($TempSrc);
		
	// 	//Get file extension from Image name, this will be added after random name
	// 	$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
	//   	$ImageExt = str_replace('.','',$ImageExt);
		
	// 	//remove extension from filename
	// 	$ImageName 		= preg_replace("/\\.[^.\\s]{3,4}$/", "", $ImageName); 
		
	// 	//Construct a new name with random number and extension.
	// 	$NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt;
		
	// 	//set the Destination Image
	// 	$thumb_DestRandImageName 	= $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumbnail name with destination directory
	// 	$DestRandImageName 			= $DestinationDirectory.$NewImageName; // Image with destination directory
		
	// 	//Resize image to Specified Size by calling resizeImage function.
	// 	if($this->resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType))
	// 	{
	// 		/*
	// 		We have succesfully resized and created thumbnail image
	// 		We can now output image to user's browser or store information in the database
	// 		*/

	// 		echo "<input type='hidden' name='foto_name' id='foto_name' value='pro_desain_promo/images/" . $NewImageName . "'>";

	// 		echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
	// 		echo '<tr>';
	// 		echo '<td align="center"><img width="300" src="' . base_url() . 'pro_desain_promo/images/'.$NewImageName.'" alt="Resized Image"></td>';
	// 		echo '</tr>';
	// 		echo '</table>';

	// 		/*
	// 		// Insert info into database table!
	// 		mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath)
	// 		VALUES ($DestRandImageName, $thumb_DestRandImageName, 'uploads/')");
	// 		*/

	// 	}else{
	// 		die('Resize Error'); //output error
	// 	}
	// }

	// function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)
	// {
	// 	//Check Image size is not 0
	// 	if($CurWidth <= 0 || $CurHeight <= 0) 
	// 	{
	// 		return false;
	// 	}
		
	// 	//Construct a proportional size of new image
	// 	$ImageScale      	= min($MaxSize/$CurWidth, $MaxSize/$CurHeight); 
	// 	$NewWidth  			= ceil($ImageScale*$CurWidth);
	// 	$NewHeight 			= ceil($ImageScale*$CurHeight);
	// 	$NewCanves 			= imagecreatetruecolor($NewWidth, $NewHeight);
		
	// 	// Resize Image
	// 	if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))
	// 	{
	// 		switch(strtolower($ImageType))
	// 		{
	// 			case 'image/png':
	// 				imagepng($NewCanves,$DestFolder);
	// 				break;
	// 			case 'image/gif':
	// 				imagegif($NewCanves,$DestFolder);
	// 				break;			
	// 			case 'image/jpeg':
	// 			case 'image/pjpeg':
	// 				imagejpeg($NewCanves,$DestFolder,$Quality);
	// 				break;
	// 			default:
	// 				return false;
	// 		}
	// 	//Destroy image, frees memory	
	// 	if(is_resource($NewCanves)) {imagedestroy($NewCanves);} 
	// 	return true;
	// 	}

	// }

	
	// function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType)
	// {	 
	// 	//Check Image size is not 0
	// 	if($CurWidth <= 0 || $CurHeight <= 0) 
	// 	{
	// 		return false;
	// 	}
		
	// 	//abeautifulsite.net has excellent article about "Cropping an Image to Make Square bit.ly/1gTwXW9
	// 	if($CurWidth>$CurHeight)
	// 	{
	// 		$y_offset = 0;
	// 		$x_offset = ($CurWidth - $CurHeight) / 2;
	// 		$square_size 	= $CurWidth - ($x_offset * 2);
	// 	}else{
	// 		$x_offset = 0;
	// 		$y_offset = ($CurHeight - $CurWidth) / 2;
	// 		$square_size = $CurHeight - ($y_offset * 2);
	// 	}
		
	// 	$NewCanves 	= imagecreatetruecolor($iSize, $iSize);	
	// 	if(imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size))
	// 	{
	// 		switch(strtolower($ImageType))
	// 		{
	// 			case 'image/png':
	// 				imagepng($NewCanves,$DestFolder);
	// 				break;
	// 			case 'image/gif':
	// 				imagegif($NewCanves,$DestFolder);
	// 				break;			
	// 			case 'image/jpeg':
	// 			case 'image/pjpeg':
	// 				imagejpeg($NewCanves,$DestFolder,$Quality);
	// 				break;
	// 			default:
	// 				return false;
	// 		}
	// 	//Destroy image, frees memory	
	// 	if(is_resource($NewCanves)) {imagedestroy($NewCanves);} 
	// 	return true;

	// 	}
		  
	// }

	// function images($filename){
		
	// 	$path = APPPATH . 'file/desain/' . $filename;
		
	// 	if(file_exists($path)){
	// 		$size = getimagesize($path);
	// 		header("Content-type: {$size['mime']}");
	// 		echo file_get_contents($path);
	// 	}else{
	// 		echo "File Not Found";
	// 	}

	// }
}


?>